package com.zj.leetcode.easy.hash;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @program: algorithm
 * @description: 两个数组的交集 II
 * 350 intersection-of-two-arrays-ii
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class IntersectionOfTwoArraysIi {
    public static void main(String[] args) {
        Solution solution = new IntersectionOfTwoArraysIi().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int[] intersect(int[] nums1, int[] nums2) {
            if (nums1.length <= 0 || nums2.length <= 0) {
                return new int[]{};
            }

            HashMap<Integer, Integer> map = new HashMap<>(16);

            for (int i = 0; i < nums1.length; i++) {
                map.put(nums1[i], map.getOrDefault(nums1[i], 0) + 1);
            }

            ArrayList<Integer> list = new ArrayList<>();
            for (int i = 0; i < nums2.length; i++) {
                if (map.containsKey(nums2[i])) {
                    Integer temp = map.get(nums2[i]);
                    if(temp > 0){
                        map.put(nums2[i], temp - 1);
                        list.add(nums2[i]);
                    }
                }
            }

            return list.stream().mapToInt(Integer::intValue).toArray();

        }
    }




//leetcode submit region end(Prohibit modification and deletion)

}
